package Dao;


import org.apache.commons.lang3.StringUtils;

import java.sql.*;
import java.util.function.Function;

public class MysqlDao {
    /**
     * 执行update、insert、delete等语句，返回值为受影响的行数
     *
     * @param sql
     * @return
     */
    public static int executeUpdate(String sql) {
        int resCount = 0;
        if (StringUtils.isBlank(sql)) {
            System.out.println("sql语句不能为空");
            return resCount;
        }
        Connection connection = null ;
        PreparedStatement ps = null;
        try {
            connection = MysqlConnPool.getConnection();
            ps = connection.prepareStatement(sql);
            resCount = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                closeConn(connection, ps, null);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return resCount;

    }

    /**
     * 执行能够返回结果集的查询语句
     *
     * @param sql
     * @return
     */
    public static Object executeQuery(String sql, Function function) {
        if (StringUtils.isBlank(sql)) {
            System.out.println("sql语句不为空");
            return null;
        }
        Connection connection = null ;
        ResultSet rs = null;
        PreparedStatement ps = null;
        try {
            connection = MysqlConnPool.getConnection();
            ps = connection.prepareStatement(sql);
            rs = ps.executeQuery();
            return function.apply(rs);
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        } finally {
            try {
                closeConn(connection, ps, null);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }



    public static void closeConn(Connection connection, Statement statement,ResultSet resultSet) throws SQLException {
        if (resultSet != null){
            resultSet.close();
        }
        if (statement != null){
            statement.close();
        }
        if (connection !=null){
            connection.close();
        }
    }
}
